﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System.Transactions;

namespace B.S.BasicData.Api.Write.Application.Handler
{
    public class AddUserRoleHandler : IRequestHandler<AddUserRoleCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<UserRoleModel> useRoleRepo;
        private readonly IMapper mapper;

        public AddUserRoleHandler(IBaseRepository<UserRoleModel> useRoleRepo,IMapper mapper)
        {
            this.useRoleRepo = useRoleRepo;
            this.mapper = mapper;
        }
        /// <summary>
        /// 用户分配角色
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<int>> Handle(AddUserRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            using (TransactionScope tran=new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    var result = useRoleRepo.GetAll().Where(x => x.RoleId == request.RoleId).ToList();
                    useRoleRepo.Delete(result);
                    List<UserRoleModel> userRoles = new List<UserRoleModel>();
                    foreach (var item in request.UserId)
                    {
                        userRoles.Add(new UserRoleModel()
                        {
                            UserId = item,
                            RoleId = request.RoleId
                        });
                    }
                    int count = useRoleRepo.AddAsnyc(userRoles);
                    if (count > 0)
                    {
                        res.Code = ApiEnum.Success;
                        res.Data = count;
                        res.Msg = "分配成功";
                    }
                    else
                    {
                        res.Code = ApiEnum.Error;
                        res.Data = count;
                        res.Msg = "分配失败";
                    }   
                    tran.Complete();
                    return Task.FromResult(res);
                }
                catch (Exception)
                {

                    throw;
                }
                
            }
        }
    }
}
